#ifndef MATERIAL_MANAGER
#define MATERIAL_MANAGER

#include "stdafx.h"

extern LPDIRECT3DDEVICE9 g_pD3DDevice;

class XBase
{
	virtual int GetType() const { return X_BASE; }
	virtual ~XBase(){};
};

class Material : XBase
{
	int GetType() const { return X_MATERIAL; }
	Material()
	{
		m_id	= -1;
		memset(m_textureFileName, 0, sizeof(m_textureFileName));
		m_hasTexture = false;
		memset(m_name, 0, sizeof(m_name));
		static int uniqueName = 0;
		uniqueName++;
		DBG_ASSERT(uniqueName<100000);
		sprintf(m_name, "RandomName%06d", uniqueName);
		m_next	= NULL;
		m_pTexture = NULL;
	}
	~Material()
	{
		if (m_pTexture)
		{
			m_pTexture->Release();
			m_pTexture = NULL;
		}
	}

	void LoadTexture(IDirect3DDevice9* pDevice, const char* folder)
	{
		if (!m_hasTexture) return;

		int len = (int)strlen(m_textureFileName);

		int iIndex = len;
		while( (iIndex>0) && (m_textureFileName[iIndex--]!= '\\' ) );
		DBG_ASSERT(iIndex>=0 && iIndex<127);

		DBG_ASSERT(len<127);
		DBG_ASSERT(iIndex>=0 && iIndex<127);
		char szFileName[256] = {0};
		int folderLen = (int)strlen(folder);
		DBG_ASSERT(folderLen+len < 255);
		strcpy( szFileName, folder);
		strcat( szFileName, &(m_textureFileName[iIndex]));

		HRESULT hr = 
			D3DXCreateTextureFromFile(	pDevice, 
			szFileName, 
			&m_pTexture );
		//DBG_ASSERT(hr);
		int correct = S_OK;
	}

	int					m_id;
	char				m_name[128];
	Material*			m_next;
	float				m_faceColourRGBA[4];
	bool				m_hasTexture;
	char				m_textureFileName[128];

	IDirect3DTexture9*	m_pTexture;
};

class MaterialManager
{
	MaterialManager()
	{
		m_materials = NULL;
	}

	~MaterialManager()
	{
		Material* tmp = m_materials;
		while (tmp)
		{
			Material* mat = tmp;
			tmp = tmp->m_next;
			delete mat;
			mat = NULL;
		}
	}

	Material* AddMaterial()
	{
		Material* newMat = new Material();
		int id = 0;
		if (m_materials)
		{
			Material* tmp = m_materials;
			while (tmp)
			{
				id++;
				if (tmp->m_next==NULL)
				{
					break;
				}
				tmp = tmp->m_next;
			}
			tmp->m_next = newMat;
		}
		else
		{
			m_materials = newMat;
		}

		newMat->m_id = id;
		return newMat;
	}

	Material* FindMaterial(const char* matName) const
	{
		Material* mat = m_materials;
		while (mat)
		{
			if (_stricmp(mat->m_name, matName)==0)
			{
				return mat;
			}
			mat = mat->m_next;
		}
		return NULL;
	}

	Material* GetMaterial(const int id) const
	{
		Material* mat = m_materials;
		while (mat)
		{
			if (mat->m_id == id)
			{
				return mat;
			}
			mat = mat->m_next;
		}
		return NULL;

	}

	void LoadTextures(char* folder)
	{
		Material* mat = m_materials;
		while(mat)
		{
			mat->LoadTexture(g_pD3DDevice, folder);
			mat = mat->m_next;
		}

	}


	Material* m_materials;
};

#endif